//
//  YRStoreManager.m
//  yanyi
//
//  Created by dyy-ios4 on 2023/6/20.
//

#import "YRStoreManager.h"
#import <StoreKit/StoreKit.h>
#import "MemberCenterViewModel.h"


@interface YRStoreManager ()<SKProductsRequestDelegate,SKPaymentTransactionObserver>

@property (nonatomic,strong) SKProductsRequest *request;//当前内购请求

@property (nonatomic, copy) IAPCompletionHandle resuldHandleBlock; //结果回调

@property (nonatomic, copy) NSString *currentBuyId; //当前购买商品回调

@property (nonatomic, copy) NSString *orderId; //当前的订单ID

@property (nonatomic, assign) BOOL isRecharge; //是否是充值


@end

@implementation YRStoreManager 

+ (id)shareManager {
    static YRStoreManager *payManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        @synchronized(self){
            payManager = [[self alloc]init];
            //获取所有属性
        }
    });
    return payManager;
}

//开始购买
- (void)startPurchaseWithID:(NSString *)purchID orderId:(NSString *)orderId isRechange:(BOOL)isRecharge completeHandle:(IAPCompletionHandle)handle{
    if (purchID.length == 0 || purchID == nil ) {
        [self handleActionWithType:IAPPurchGoodsMessageError message:@"没有商品信息"];
    } else {
        self.resuldHandleBlock = handle;
        if ([SKPaymentQueue canMakePayments]) {
            self.currentBuyId = purchID;
            self.orderId = orderId;
            self.isRecharge = isRecharge;
            //从App Store中检索关于指定产品列表的本地化信息
            NSSet *nsset = [NSSet setWithArray:@[purchID]];
            SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
            request.delegate = self;
            [request start];
            self.request = request;
        } else {
            [self handleActionWithType:IAPPurchNotAllow message:@"不允许内购"];
        }
    }
    
}

- (void)handleActionWithType:(IAPPurchType)type message:(NSString *)message {
    switch (type) {
        case IAPPurchSuccess:
            NSLog(@"购买成功");
            break;
        case IAPPurchFailed:
            NSLog(@"购买失败");
            break;
        case IAPPurchCancel:
            NSLog(@"用户取消购买");
            break;
        case IAPPurchVerFailed:
            NSLog(@"订单校验失败");
            break;
        case IAPPurchVerSuccess:
            NSLog(@"订单校验成功");
            break;
        case IAPPurchNotAllow:
            NSLog(@"不允许程序内付费");
            break;
        default:
            break;
    }
    if(self.resuldHandleBlock){
        self.resuldHandleBlock(type,message);
    }
}

//MARK: - SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    if(response.products.count <= 0){
        NSLog(@"--------------没有商品------------------");
        [self handleActionWithType:IAPPurchGoodsMessageError message:@"没有商品信息"];
        return;
    }
     
    SKProduct *outProduct = nil;
    for(SKProduct *product in response.products){
        if([product.productIdentifier isEqualToString:self.currentBuyId]){
            outProduct = product;
            break;
        }
    }
     
#if DEBUG
//    NSLog(@"productID:%@", response.invalidProductIdentifiers);
//    NSLog(@"产品付费数量:%lu",(unsigned long)[product count]);
//    NSLog(@"产品描述:%@",[p description]);
//    NSLog(@"产品标题%@",[p localizedTitle]);
//    NSLog(@"产品本地化描述%@",[p localizedDescription]);
//    NSLog(@"产品价格：%@",[p price]);
//    NSLog(@"产品productIdentifier：%@",[p productIdentifier]);
#endif
    SKPayment *payment = [SKPayment paymentWithProduct:outProduct];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

//请求成功
- (void)requestDidFinish:(SKRequest *)request  {
    
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [self handleActionWithType:IAPPurchGoodsMessageError message:@"商品信息请求失败"];
    NSLog(@"------------------从App Store中检索关于指定产品列表的本地化信息错误-----------------:%@", error);
}



//MARK: - SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *tran in transactions) {
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                [self verifyPurchaseWithPaymentTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"恢复购买");
                // 消耗型不支持恢复购买
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:tran];
                break;
            default:
                break;
        }
    }
}

- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction {
    //交易验证
    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
    NSString *receiptString = [receipt base64EncodedStringWithOptions:0];
    
    if(!receipt){
        // 交易凭证为空验证失败
        [self handleActionWithType:IAPPurchVerFailed message:@"订单校验失败"];
        return;
    }
//

    if (receiptString.length == 0 || receipt == nil) {
        [self handleActionWithType:IAPPurchVerFailed message:@"订单校验失败"];
        return;
    }
    if (!self.isRecharge) {
        //会员
//        [MemberCenterViewModel confirmBuyResultWithreceiptData:receiptString orderNumber:self.orderId Completion:^(NSObject * _Nonnull model, BOOL success, NSString * _Nonnull errorMessage) {
//            if (success) {
//                [self handleActionWithType:IAPPurchSuccess message:@"购买成功"];
//            } else {
//                [self handleActionWithType:IAPPurchVerFailed message:@"订单校验失败"];
//            }
//        }];
        [MemberCenterViewModel confirmRechargeResultWithreceiptData:receiptString orderNumber:self.orderId rechargeID:self.currentBuyId Completion:^(NSObject * _Nonnull model, BOOL success, NSString * _Nonnull errorMessage) {
            if (success) {
                [self handleActionWithType:IAPPurchSuccess message:@"购买成功"];
            } else {
                [self handleActionWithType:IAPPurchVerFailed message:@"订单校验失败"];
            }
        }];
    } else {
        [MemberCenterViewModel confirmRechargeResultWithreceiptData:receiptString orderNumber:self.orderId rechargeID:self.currentBuyId Completion:^(NSObject * _Nonnull model, BOOL success, NSString * _Nonnull errorMessage) {
            if (success) {
                [self handleActionWithType:IAPPurchSuccess message:@"购买成功"];
            } else {
                [self handleActionWithType:IAPPurchVerFailed message:@"订单校验失败"];
            }
        }];
    }
    
     
    // 验证成功与否都注销交易,否则会出现虚假凭证信息一直验证不通过,每次进程序都得输入苹果账号
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

// 交易失败
- (void)failedTransaction:(SKPaymentTransaction *)transaction{
    if (transaction.error.code != SKErrorPaymentCancelled) {
        [self handleActionWithType:IAPPurchFailed message:@"购买失败"];
    }else{
        [self handleActionWithType:IAPPurchCancel message:@"购买取消"];
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

@end
